package com.zany.net;

import com.zany.net.codec.MyMessageDecoder;
import com.zany.net.codec.MyMessageEncoder;
import com.zany.util.file.SCacheManage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.InetSocketAddress;

/**
 * Servlet implementation class for Servlet: HouseServer
 * 
 */
public class HotServer implements ServletContextListener {

	private static Log logger = LogFactory.getLog(HotServer.class);
	private Integer serverport;

	public void contextInitialized(ServletContextEvent arg0) {
		if (logger.isInfoEnabled()) {logger.info("HotServer.contextInitialized()");}
		NioSocketAcceptor acceptor;
		try {
			ServletContext servletContext = arg0.getServletContext();
			WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
			serverport = Integer.parseInt(SCacheManage.getInstance().getValue("hotserver", "serverport"));
			acceptor = new NioSocketAcceptor();
			// 设置线程池，以支持多线程
			DemuxingProtocolCodecFactory pcf = new DemuxingProtocolCodecFactory();
			// 自定义编码器
			pcf.addMessageEncoder(String.class, new MyMessageEncoder());
			// 自定义解码器
			pcf.addMessageDecoder(new MyMessageDecoder());
			ProtocolCodecFilter codec = new ProtocolCodecFilter(pcf);
			acceptor.getSessionConfig().setReadBufferSize(4096);
			acceptor.getSessionConfig().setReceiveBufferSize(4096);
			acceptor.getFilterChain().addLast("codec", codec);// 指定编码过滤器
			acceptor.setReuseAddress(true);
			acceptor.setHandler(new ServerHandler(webApplicationContext));// 指定业务逻辑处理器
			acceptor.setDefaultLocalAddress(new InetSocketAddress(serverport));// 设置端口号
			acceptor.bind();// 启动监听
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}
}